package org.example.demo1.filter;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.example.demo1.Entity.User;

import java.awt.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;


@WebFilter(urlPatterns = {"/MainPage/managePage/*"}, dispatcherTypes = {DispatcherType.REQUEST})
public class LimitsFilter implements Filter {
    private String encoding = "UTF-8";
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;

        HttpServletResponse res = (HttpServletResponse) servletResponse;
        // 获取 Session（不创建新的）
        HttpSession session = req.getSession();
        User user= (User) session.getAttribute("user");
        ArrayList<Integer> permissionList= (ArrayList<Integer>) session.getAttribute("permission");

        boolean permissionLimit=false;
        for(Integer permission:permissionList){
            if(permission==8){
                permissionLimit=true;
                break;
            }
        }
        
        // 修改：使用role_id替代user_role
        if (user != null && permissionLimit){
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            res.sendRedirect(req.getContextPath() + "/login.jsp?errorCode=2");
            return;
        }
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
